package com.lin.mr.maizilaundry.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lin.mr.maizilaundry.R;
import com.lin.mr.maizilaundry.utils.CountEvent;

import de.greenrobot.event.EventBus;
import zhy.com.highlight.HighLight;

public class LoginActivity2 extends Activity implements View.OnClickListener {
    private ImageView btn_back_login;
    private TextView btn_to_register;
    private EditText et_phone_number;
    //发送短信验证码的按钮
    private Button btn_Captcha;
    private EditText et_Captcha;
    private Button btn_login;
    private TextView tv_agreement;
    private LinearLayout register_layout;

    private HighLight highLight;
    private Boolean isNumber;

    private CountTimer countTimer;

    private String randomCode;//随机数(验证码)


    private void initViews() {
        //初始化控件
        btn_back_login = (ImageView) findViewById(R.id.btn_back_login);
        btn_to_register = (TextView) findViewById(R.id.btn_to_register);
        et_phone_number = (EditText) findViewById(R.id.et_phone_number);
        btn_Captcha = (Button) findViewById(R.id.btn_captcha);
        et_Captcha = (EditText) findViewById(R.id.et_captcha);
        btn_login = (Button) findViewById(R.id.btn_login);
        tv_agreement = (TextView) findViewById(R.id.tv_agreement);
        register_layout = (LinearLayout) findViewById(R.id.register_layout);

        countTimer = new CountTimer(20000, 1000);//传入倒计时的总时间和间隔

        //设置监听事件
        tv_agreement.setOnClickListener(this);
        btn_Captcha.setOnClickListener(this);
        btn_back_login.setOnClickListener(this);
        btn_to_register.setOnClickListener(this);
        btn_login.setOnClickListener(this);

        //必须用post方法通知更新线程，否则会报空指针
        btn_to_register.post(new Runnable() {
            @Override
            public void run() {
                tipForRegister();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initViews();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        countTimer.cancel();//关闭倒计时
    }

    // 判断用户输入的手机号码是否正确
    public boolean isPhoneNumber(String str) {
        String strRegex = "[1][34578]\\d{9}";
        boolean result = str.matches(strRegex);
        return result;
    }

    @Override
    public void onClick(View v) {
        String phoneNum = et_phone_number.getText().toString().trim();//获取手机号码
        String captcha = et_Captcha.getText().toString().trim();//获取验证码
        switch (v.getId()) {
            case R.id.btn_to_register:
                startActivity(new Intent(LoginActivity2.this, RegisterActivity.class));
                break;
            case R.id.btn_captcha: //发送验证码
                isNumber = isPhoneNumber(phoneNum);
                if (isNumber == true) {
                    countTimer.start();//点击按钮开始倒计时
                    getRandom();//发送验证码
                } else {
//                    et_phone_number.setError(Html.fromHtml("<font color=red>您输入的手机号码有误！</font>"));
                    Toast.makeText(this, "您输入的手机号码有误！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_agreement:
                startActivity(new Intent(LoginActivity2.this, WebViewActivity.class));
                break;
            case R.id.btn_back_login:
                startActivity(new Intent(LoginActivity2.this,HomeActivity.class));
                finish();
                break;
            case R.id.btn_login:
//
                if (!TextUtils.isEmpty(captcha) && isNumber == true) {//判断验证码是否为空
                    Log.e("tag", "randomCode:" + randomCode + "captcha:" + captcha);
                    //不能将两个字符串直接用“==”判断
                    if (Integer.parseInt(captcha) == Integer.parseInt(randomCode)) {
                        SharedPreferences sp = getSharedPreferences("UserInfo", MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("phoneNumber", phoneNum);
                        editor.commit();
                        startActivity(new Intent(LoginActivity2.this, HomeActivity.class));
                        EventBus.getDefault().post(new CountEvent(3));//通知HomeActivity刷新数据
                    } else {
                        et_Captcha.setError(Html.fromHtml("<font color=red>验证码输入有误！</font>"));

                    }
                } else {
                    et_Captcha.setError(Html.fromHtml("<font color=red>请输入验证码！</font>"));
                }

                break;
        }
    }

    //获取4位随机数
    private void getRandom() {
        //定义一个随机字符串
        final String RANDOMS = "0123456789";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            int random = (int) (Math.random() * RANDOMS.length());
            buffer.append(RANDOMS.charAt(random));
        }
        //生成一个随机数
        randomCode = buffer.toString();
        //
        Message msg = new Message();
        msg.what = 100;
        msg.obj = randomCode;
        //延迟3s发送
        handler.sendMessageDelayed(msg, 3000);

    }

    //在Handler中显示Toast
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                Toast.makeText(LoginActivity2.this, "验证码为:" + msg.obj, Toast.LENGTH_SHORT).show();
            }
        }
    };

    //发送验证码之后进行60s倒计时
    public class CountTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //倒计时期间调用的方法
        @Override
        public void onTick(long millisUntilFinished) {
            btn_Captcha.setText(millisUntilFinished / 1000 + "秒后重新发送");
            btn_Captcha.setTextSize(14);//将按钮上的文字字体修改小一点
            btn_Captcha.setClickable(false);//倒计时期间按钮不能点击
        }

        //倒计时结束之后回调的方法
        @Override
        public void onFinish() {
            btn_Captcha.setText("重新发送");
            btn_Captcha.setClickable(true);
        }
    }

    //对注册按钮进行高亮提示
    public void tipForRegister() {
        highLight = new HighLight(LoginActivity2.this);
        highLight.anchor(register_layout);//指明需要加上透明蒙版的view
        highLight.addHighLight(R.id.btn_to_register, R.layout.tip_register, new HighLight.OnPosCallback() {
            @Override
            public void getPos(float rightMargin, float bottomMargin, RectF rectF, HighLight.MarginInfo marginInfo) {
                //下面两行不是很明白
                /**
                 * @param rightMargin 高亮view在anchor中的右边距
                 * @param bottomMargin 高亮view在anchor中的下边距
                 * @param rectF 高亮view的l,t,r,b,w,h都有
                 * @param marginInfo 设置你的布局的位置，一般设置l,t或者r,b
                 */
                //指示图案在布局中的右边距，跟“注册”按钮一致即可
                marginInfo.rightMargin = rightMargin;
                //指示图案在布局中的上边距，要在“注册”按钮的下方，所以要加上“注册”按钮的
                marginInfo.topMargin = rectF.top + rectF.height();
            }
        });
        highLight.show();
    }
}
